/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.ttt.nor2.thread;

import com.ttt.nor2.db.Smstrans;
import com.ttt.nor2.util.ExceptionUtil;
import com.ttt.nor2.util.StopWatch;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.apache.log4j.Logger;

/**
 *
 * @author anuphabm
 */
public class ThPostsms extends Thread {

    private Logger logger = Logger.getLogger(ThPostsms.class);
    private Smstrans smst;
    private HttpClient http;
    private static int thWork;

    public static int getThWork() {
        return thWork;
    }

    static synchronized void incThread() {
        thWork++;
    }

    synchronized void decThread() {
        thWork--;
    }

    public ThPostsms(Smstrans smst, HttpClient http) {
        this.smst = smst;
        this.http = http;
        incThread();
        logger.debug("Thread working...[" + thWork + "]");

        //config http client
        confHttp();
    }

    @Override
    public void run() {

        PostMethod post = null;
        StopWatch sw = null;
        int time = 0;

        try {
            post = new PostMethod(smst.getScript());
            //get param
            String qStr = getParam();
            logger.info("Post to value :[" + qStr + "]");
            sw = new StopWatch();
            sw.doStart();

            RequestEntity e = new StringRequestEntity(qStr, "application/x-www-form-urlencoded", "TIS-620");
            post.setRequestEntity(e);
            post.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

            http.executeMethod(post);
            InputStream is = post.getResponseBodyAsStream();
            String line;
            BufferedReader brd = new BufferedReader(new InputStreamReader(is));
            StringBuffer strbuff = new StringBuffer();
            while ((line = brd.readLine()) != null) {
                String newLine = line + "\n";
                strbuff.append(newLine);
            }
            String rspRtn = strbuff.toString();
            logger.info("[" + smst.getAni() + "][" + smst.getTransid() + "]status code[" + post.getStatusCode() + "]Post result [" + rspRtn + "]");
            time = Integer.parseInt(sw.doStop());

            if (post.getStatusCode() == HttpStatus.SC_OK || post.getStatusCode() == 202) {
                //sendtime, result, statuscode, ondate, duration, result_count, status="y"
                smst.setResult("OK");
                smst.setStatuscode(post.getStatusCode());
            } else {
                smst.setResult("ERR " + post.getStatusLine().getReasonPhrase());
                smst.setStatuscode(post.getStatusCode());
            }

        } catch (Exception e) {
            logger.error("Exception run thread error!" + ExceptionUtil.getStackTrace(e));
        } finally {
            post.releaseConnection();
            logger.info("[" + smst.getTransid() + "] Update status [Y]");
            smst.setTime(time);
            //smst.setStatus(smst.getTransid(), "Y");
            smst.udSmst();
            logger.info("[" + smst.getAni() + "] post to server done. " + time + " mSec.");
            decThread();
        }
    }

    private void confHttp() {
        logger.info("[" + smst.getAni() + "]Post to url " + smst.getUrlhttp() + " Port " + smst.getPorthttp());
        logger.info("[" + smst.getAni() + "]Script : " + smst.getScript());
        http.getHostConfiguration().setHost(smst.getUrlhttp(), smst.getPorthttp(), "http");
        if (smst.getUrlproxy() != null) {
            logger.info("[" + smst.getAni() + "]Now used Proxy Server " + smst.getUrlproxy() + " Port " + smst.getPortproxy());
            http.getHostConfiguration().setProxy(smst.getUrlproxy(), smst.getPortproxy());
        }
    }

    private String getParam() {
        StringBuffer stb = new StringBuffer();
        stb.append("user_id=").append(smst.getUsername()).append("&send_no_dis=").append(smst.getSender());
        stb.append("&type=").append(smst.getType()).append("&lang=").append(smst.getLang()).append("&msgcnt=1&");
        stb.append("&tel_no=").append(smst.getAni()).append("&msg=").append(smst.getMsgout());
        return stb.toString();
    }
}
